//
//  UIImage+JKRShareManagerCategory.m
//  JKRShareManager
//
//  Created by Lucky on 2018/6/29.
//

#import "UIImage+JKRShareManagerCategory.h"

@implementation UIImage (JKRShareManagerCategory)

- (void)jkr_share_manager_compressToDataLength:(NSInteger)length withBlock:(void (^)(NSData *))block {
    if (length <= 0 || [self isKindOfClass:[NSNull class]] || self == nil) block(nil);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        UIImage *newImage = [self copy];
        {
            CGFloat clipScale = 0.9;
            NSData *pngData = UIImagePNGRepresentation(self);
            NSLog(@"Original pnglength %zd", pngData.length);
            NSData *jpgData = UIImageJPEGRepresentation(self, 1.0);
            NSLog(@"Original jpglength %zd", jpgData.length);
            while (jpgData.length > length) {
                NSData *newImageData = UIImageJPEGRepresentation(newImage, 0.0);
                if (newImageData.length < length) {
                    CGFloat scale = 1.0;
                    newImageData = UIImageJPEGRepresentation(newImage, scale);
                    while (newImageData.length > length) {
                        scale -= 0.1;
                        newImageData = UIImageJPEGRepresentation(newImage, scale);
                    }
                    dispatch_async(dispatch_get_main_queue(), ^{
                        NSLog(@"Result jpglength %zd", newImageData.length);
                        block(newImageData);
                    });
                    return;
                } else {
                    newImage = [newImage jkr_share_manager_compressWithWidth:newImage.size.width * clipScale];
                    jpgData = UIImageJPEGRepresentation(newImage, 1.0);
                }
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"Result jpglength %zd", jpgData.length);
                block(jpgData);
            });
        }
    });
}

- (UIImage *)jkr_share_manager_compressWithWidth:(CGFloat)width {
    if (width <= 0 || [self isKindOfClass:[NSNull class]] || self == nil) return nil;
    CGSize newSize = CGSizeMake(width, width * (self.size.height / self.size.width));
    UIGraphicsBeginImageContext(newSize);
    [self drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

@end
